<template>
  <div class="app-container home">
    <MapComponent ref="mapRef"
                  @circle-update="handleCircleUpdate"
                  @polygon-update="handlePolygonUpdate"
                  :showtoolbox="isShow"
                  :showweather="isShow"
                  :showswitchbox="isShow"/>
     <!--右侧侧边栏-->
     <div class="sidebar">
      <h2>系统禁飞区</h2>
      <hr class="sidebar-divider">
      <el-input v-model="searchKeyword" type="text" placeholder="搜索" @keyup.enter="handleQuery"/>
      <div class="zones-list-container">
        <ul>
          <!-- 列表内容 -->
          <div class="infor-container"
               v-for="(zone, index) in allUnflyZones"
               :key="index">
            <div class="infor" @click="focusOnZone(zone)">
              {{ zone.name }}
              <el-button
                  class="delete-btn custom-delete-btn"
                  type="primary"
                  size="default"
                  @click="deleteZone(zone)">
                删除
              </el-button>
            </div>
          </div>
        </ul>
      </div>
      <hr class="sidebar-divider">
      <el-button @click="xjjfq" type="primary" class="add-zone-btn">新建禁飞区</el-button>
    </div>

    <!--环形禁飞区左侧侧边栏（初始隐藏）-->
    <div v-if="showSidebarLeft" class="sidebarleft">
      <h2>环形禁飞区</h2>
      <hr class="sidebarleft-divider">

      <ul>
        <!-- 列表内容 -->
        <div class="type-section">
          <div class="type-label">类型</div>
          <div class="type-value">
            <div class="type-box">环形</div>
          </div>
        </div>
        <div class="center-coordinate">
          <div class="coordinate-label">中心坐标</div>
          <div class="coordinate-value">
            <el-input v-model="centerCoordinate" type="text" placeholder="经纬度" />
          </div>
        </div>

        <div class="center-coordinate">
          <div class="coordinate-label">半径（米）</div>
          <div class="coordinate-value">
            <el-input v-model="radius" type="text" placeholder="米" />
          </div>
        </div>
      </ul>
      <hr class="sidebarleft-divider">
      <div class="tong">
        <!-- 直接传递值 -->
        <el-button v-if="showHxQd" @click="addCircle(centerCoordinate, radius)" type="primary" size="large" style="margin-left: 25px">确定</el-button>
        <el-button @click="cancelCircle" type="info" size="large" style="margin-right: 25px">取消</el-button>
      </div>
    </div>

    <!-- 多边形侧边栏（初始隐藏） -->
    <div v-if="showPolygonSidebar" class="sidebarleft">
      <h2>多边形禁飞区</h2>
      <hr class="sidebarleft-divider">

      <ul>
        <div class="type-section">
          <div class="type-label">类型</div>
          <div class="type-value">
            <div class="type-box">多边形</div>
          </div>
        </div>

        <div class="center-coordinate">
          <div class="coordinate-label">中心坐标</div>
          <div class="coordinate-value">
            <el-input v-model="polygonCenterCoordinate" type="text" placeholder="经纬度" readonly />
          </div>
        </div>

        <div class="point-settings">
          <div class="point-title">单点设置</div>
          <div class="point-selector">
            <el-select v-model="selectedPointIndex" placeholder="请选择点">
              <el-option
                  v-for="(point, index) in polygonPoints"
                  :key="index"
                  :label="`点 ${index + 1}`"
                  :value="index"
              />
            </el-select>
          </div>
          <div class="point-coordinates">
            <div class="coordinate-row">
              <span class="coord-label">经度</span>
              <el-input v-model="currentPoint.longitude" readonly class="fule"/>
            </div>
            <div class="coordinate-row">
              <span class="coord-label">纬度</span>
              <el-input v-model="currentPoint.latitude" readonly class="fu"/>
            </div>
          </div>
        </div>
      </ul>

      <hr class="sidebarleft-divider">
      <div class="tong">
        <el-button v-if="showDbxQd" @click="addPolygon" type="primary" size="large" style="margin-left: 25px">确定</el-button>
        <el-button @click="cancelPolygon" type="info" size="large" style="margin-right: 25px">取消</el-button>
      </div>
    </div>

    <!--新建禁飞区弹窗-->
    <div v-if="showModal" class="modal">
      <div class="modal-content">
        <h3>新建禁飞区</h3>
        <hr class="modal-divider">
        <!-- 新建禁飞区弹窗中的按钮组部分修改 -->
        <div class="button-group">
          <div class="button-item" @click="selectDrawType('polygon')">
            <img src="@/assets/images/polygon.png" class="button-icon">
            <el-button :class="{ 'active': selectedDrawType === 'polygon' }">
              多边形禁飞区
            </el-button>
          </div>
          <div class="button-item" @click="selectDrawType('circle')">
            <img src="@/assets/images/circle.png" class="button-icon">
            <el-button :class="{ 'active': selectedDrawType === 'circle' }">
              环形禁飞区
            </el-button>
          </div>
        </div>
        <hr class="modal-divider">
        <div class="action-buttons">
          <el-button @click="showModal = false">取消</el-button>
          <el-button
              @click="confirmDraw"
              type="primary"
          >
            确定
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import MapComponent from "@/components/MapComponent/index.vue";
import { ref, watch } from 'vue';
import { addHxUnflyZone,getHxUnflyZoneList,delHxUnflyZone } from "@/api/unflyzone/hx/hxUnfly";
import { getCurrentInstance } from 'vue';
import {addDbxUnflyZone,getDbxUnflyZoneList,deleteDbxUnflyZoneById} from "@/api/unflyzone/dbx/dbxUnfly.js";
import defaultNoFlyZone from '@/assets/resData/defaultNoFlyZone.json';
const isShow = ref(false)
const { proxy } = getCurrentInstance();
const showModal = ref(false);
const mapRef = ref(null);
const selectedDrawType = ref('');
const activeMode = ref(2);
// 控制环形左侧菜单栏的显示状态
const showSidebarLeft = ref(false);
// 新增响应式数据(环形中心坐标和半径)
const centerCoordinate = ref('')
const radius = ref('')
const showDbxQd = ref(true)
const showHxQd = ref(true)
const searchKeyword = ref('');
//新建禁飞区按钮
const xjjfq = () => {
  showModal.value = true;
  showSidebarLeft.value = false;
  showPolygonSidebar.value = false;
}
// 环形事件处理函数
const handleCircleUpdate = ({ longitude, latitude, radius: r }) => {
  centerCoordinate.value = `${longitude.toFixed(6)}, ${latitude.toFixed(6)}`
  radius.value = r.toFixed(2)
}

const selectDrawType = (type) => {
  selectedDrawType.value = type;
};

watch(showModal, (newValue) => {
  if (!newValue) {
    selectedDrawType.value = '';
  }
});

//开启绘制多边形或环形
const confirmDraw = () => {
  showHxQd.value = true;
  showDbxQd.value = true;

  // 先清理可能存在的图形
  mapRef.value.resetDrawingState();

  if (selectedDrawType.value === 'polygon') {
    showModal.value = false;
    showPolygonSidebar.value = true;
    mapRef.value.drawPolygon();
  } else if (selectedDrawType.value === 'circle') {
    showModal.value = false;
    showSidebarLeft.value = true;
    mapRef.value.drawCircle();
  }
};

//控制环形菜单栏显示与隐藏
const cancelCircle = () => {
  showSidebarLeft.value = false;
  // 重置数据
  centerCoordinate.value = '';
  radius.value = '';
  // 调用地图组件的方法清除圆形
  mapRef.value.clearCircle();
};

//新增环形禁飞区确定按钮
const addCircle = (centerCoordinate, radius) => {
  // 只有在新建时才执行提交
  console.log('addCircle: centerCoordinate', centerCoordinate);
  console.log('addCircle: radius', radius);
  if (!centerCoordinate) {
    console.error('center value is undefined');
    return;
  }
  const [longitudeStr, latitudeStr] = centerCoordinate.split(',');
  const longitude = parseFloat(longitudeStr.trim());
  const latitude = parseFloat(latitudeStr.trim());
  const r = parseFloat(radius);

  // 修改数据字段名与后端实体类一致
  addHxUnflyZone({ hxLongitude: longitude, hxLatitude: latitude, hxRadius: r }).then(response => {
    proxy.$modal.msgSuccess("新增成功");
    cancelCircle();
    getList();
  });

  showSidebarLeft.value = false;
}

// 多边形新增响应式数据
const showPolygonSidebar = ref(false);
const polygonCenterCoordinate = ref('');
const polygonPoints = ref([]);
const selectedPointIndex = ref(0);
const currentPoint = ref({
  longitude: '',
  latitude: ''
});

// 多边形更新处理函数
const handlePolygonUpdate = (data) => {
  const { polygonPoints: points, polygonCenter: center } = data;
  showPolygonSidebar.value = true;
  polygonCenterCoordinate.value = `${center.longitude.toFixed(6)}, ${center.latitude.toFixed(6)}`;
  polygonPoints.value = points;
  updateCurrentPoint(0); // 默认显示第一个点
};

// 更新当前选中的点
const updateCurrentPoint = (index) => {
  if (polygonPoints.value.length > index) {
    currentPoint.value = {
      longitude: polygonPoints.value[index].longitude.toFixed(6),
      latitude: polygonPoints.value[index].latitude.toFixed(6)
    };
  }
};

// 监听选择的点变化
watch(selectedPointIndex, (newIndex) => {
  updateCurrentPoint(newIndex);
});

// 新增多边形禁飞区确定按钮
const addPolygon = async () => {

  if (!polygonCenterCoordinate.value || polygonPoints.value.length < 3) {
    proxy.$modal.msgError("请绘制有效的多边形（至少3个顶点）");
    return;
  }

  // 转换中心点坐标
  const [centerLon, centerLat] = polygonCenterCoordinate.value.split(',').map(Number);

  // 构建顶点数据（带顺序）
  const points = polygonPoints.value.map((p, index) => ({
    pointLongitude: p.longitude,
    pointLatitude: p.latitude,
    pointOrder: index + 1
  }));

  try {
    // 发送请求
    const res = await addDbxUnflyZone({
      dbxLongitude: centerLon,
      dbxLatitude: centerLat,
      points: points
    });

    if (res.code === 200) {
      proxy.$modal.msgSuccess("新增成功");
      cancelPolygon();
      getList();
    }
  } catch (error) {
    console.error('新增失败:', error);
  }

  showPolygonSidebar.value = false;
}

// 取消多边形绘制
const cancelPolygon = () => {
  showPolygonSidebar.value = false;
  // 重置数据
  polygonCenterCoordinate.value = '';
  polygonPoints.value = [];
  selectedPointIndex.value = 0;
  currentPoint.value = { longitude: '', latitude: '' };
  // 调用地图组件的方法清除多边形
  mapRef.value.clearPolygon();
};


// 定义响应式数据来存储所有禁飞区名称
const allUnflyZones = ref([]);
//查询环形、多边形禁飞区列表
const getList = async () => {
  try {
    // 获取 viewer 对象
    const viewer = mapRef.value.getViewer();

    // 清除现有图形（重要！）
    allUnflyZones.value.forEach(zone => {
      if (viewer && zone.entity) {
        viewer.entities.removeById(zone.entity.id); // 使用 removeById 方法
      }
    });

    // 清空当前列表
    allUnflyZones.value = [];

    // 获取新数据并绘制
    const [hxResponse, dbxResponse] = await Promise.all([
      getHxUnflyZoneList({ hxName: searchKeyword.value }),
      getDbxUnflyZoneList({ dbxName: searchKeyword.value })
    ]);

    // 重新填充数据
    allUnflyZones.value = [
      ...hxResponse.rows.map(item => ({
        id: item.id,
        name: item.hxName,
        type: 'circle',
        center: [item.hxLongitude, item.hxLatitude],
        radius: item.hxRadius,
        entity: mapRef.value.drawExistingCircleJFQ(item.hxLongitude, item.hxLatitude, item.hxRadius)[0] // 确保引用第一个实体
      })),
      ...dbxResponse.rows.map(item => ({
        id: item.polygon.id,
        name: item.polygon.dbxName,
        type: 'polygon',
        center: [item.polygon.dbxLongitude, item.polygon.dbxLatitude],
        points: item.points.map(p => [p.pointLongitude, p.pointLatitude]),
        entity: mapRef.value.drawExistingPolygon(item.points.map(p => [p.pointLongitude, p.pointLatitude]))[0] // 确保引用第一个实体
      }))
    ];
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};




// 单击数据条地图跳转方法
const focusOnZone = (zone) => {
  if (zone.type === 'circle') {
    showHxQd.value = false;
    mapRef.value.flyToCircle(zone.center, zone.radius);
    showSidebarLeft.value = true;
    showPolygonSidebar.value = false;
    centerCoordinate.value = `${zone.center[0].toFixed(6)}, ${zone.center[1].toFixed(6)}`;
    radius.value = zone.radius.toFixed(2);
  } else {
    showDbxQd.value = false;
    mapRef.value.flyToPolygon(zone.center);
    showPolygonSidebar.value = true;
    showSidebarLeft.value = false;
    polygonCenterCoordinate.value = `${zone.center[0].toFixed(6)}, ${zone.center[1].toFixed(6)}`;
    polygonPoints.value = zone.points.map((point, index) => ({
      longitude: point[0],
      latitude: point[1],
      index: index + 1
    }));
    selectedPointIndex.value = 0;
    updateCurrentPoint(0);
  }
};

// 删除禁飞区
const deleteZone = async (zone) => {
  try {
    await proxy.$modal.confirm(`确定要删除禁飞区 "${zone.name}" 吗？`, '提示');

    let res;
    if (zone.type === 'circle') {
      res = await delHxUnflyZone(zone.id);
      showPolygonSidebar.value = false;
    } else {
      res = await deleteDbxUnflyZoneById(zone.id);
      showPolygonSidebar.value = false;
    }

    if (res.code === 200) {
      // 从地图上移除对应的实体
      const viewer = mapRef.value.getViewer();
      if (viewer && zone.entity) {
        viewer.entities.remove(zone.entity);
      }
      proxy.$modal.msgSuccess("删除成功");
      // 刷新列表
      getList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      proxy.$modal.msgError("删除失败");
    }
  }
};

/** 搜索按钮操作 */
function handleQuery() {
  showSidebarLeft.value = false;
  showPolygonSidebar.value = false;
  getList();
}

// 在获取地图组件引用后加载默认数据
watch(mapRef, (newVal) => {
  if (newVal) {
    // 加载默认禁飞区
    mapRef.value.loadDefaultNoFlyZones(defaultNoFlyZone);
    // 原有获取列表数据
    getList();
  }
});

/*
getList();
*/
</script>

<style scoped lang="scss">
.app-container {
  position: relative;
  width: 100%;
  height: 100vh;
}

.sidebar {
  position: absolute;
  top: 0;
  right: 0;
  width: 265px;
  height: 100vh;
  background-color: #1c1e21;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

// 新增样式：列表容器，允许滚动
.zones-list-container {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

.sidebar h2 {
  margin-top: 0;
  color: white; /* 侧边栏标题颜色为白色 */
}

.sidebar .el-input__inner {
  background-color: #333; /* 搜索框颜色为浅黑色 */
  color: white;
  border: none;
}

.sidebar ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

// 新增样式：确保按钮固定在底部
.add-zone-btn {
  margin-top: 10px;
  width: 100%;
}


.sidebar .el-button--primary {
  background-color: #1890ff; /* 新建禁飞区按钮为蓝色 */
  border-color: #1890ff;
}

.sidebar-divider {
  border: none;
  border-top: 1px solid #444;
  margin: 10px 0;
}

.sidebarleft {
  position: absolute;
  top: 0;
  right: 270px;
  width: 265px;
  height: 100vh;
  background-color: #1c1e21;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

.sidebarleft h2 {
  margin-top: 0;
  color: white; /* 侧边栏标题颜色为白色 */
}

.sidebarleft ul {
  list-style: none;
  padding: 0;
  margin: 0;
  flex-grow: 1;
}

.type-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.type-label {
  color: white;
  margin-right: 20px;
}

.type-value {
  display: flex;
  align-items: center;
}

.type-box {
  background-color: white;
  padding: 5px 10px;
  border-radius: 5px;
  color: #1890ff;
}

.center-coordinate {
  align-items: center;
  margin-bottom: 10px;
}

.coordinate-label {
  color: white;
  margin-bottom: 20px;
}

.coordinate-value {
  flex-grow: 1;
}

.sidebarleft .el-input__inner {
  background-color: #333; /* 搜索框颜色为浅黑色 */
  color: white;
  border: none;
}

.tong {
  display: flex;
  justify-content: space-between;
}

.sidebarleft .el-button--primary {
  background-color: #1890ff; /* 确定按钮为蓝色 */
  border-color: #1890ff;
}

.sidebarleft .el-button--info {
  background-color: #333; /* 取消按钮为浅黑色 */
  color: white;
  border-color: #333;
}

.sidebarleft-divider {
  border: none;
  border-top: 1px solid #444;
  margin: 10px 0;
}

// 添加多边形菜单栏样式
.polygon-sidebar {
  right: 530px; /* 调整位置，避免与环形菜单重叠 */
}

.point-title {
  color: white;
  margin-bottom: 10px;
}

.coord-label{
  color: white;
  margin-bottom: 10px;
}

.fu{
  margin-top: 10px;
}

.fule{
  margin-top: 10px;
}

.point-selector{
  margin-bottom: 10px;
}

.coordinate-row{
  margin-bottom: 10px;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 400px; /* 弹窗宽度增大 */
  height: 300px; /* 弹窗高度增大 */
  display: flex;
  flex-direction: column;
}

.modal-content h3 {
  margin-top: 0;
}

.button-group {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
}
.button-item {
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: center; /* 子元素水平居中 */
  text-align: center; /* 文本居中 */
}

.button-icon {
  width: 60px; /* 缩小图标尺寸 */
  height: 60px;
  margin-bottom: 8px; /* 图标与按钮之间的间距 */
}

/* 调整后的按钮样式 */
.button-item .el-button {
  width: 120px; /* 固定按钮宽度 */
  padding: 6px 12px; /* 调整内边距 */
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: auto;
}

.action-buttons button {
  margin-left: 10px;
}

.modal-divider {
  border: none;
  border-top: 1px solid #ccc;
  margin: 0px 0;
}

.active {
  background-color: #1890ff;
  color: white;
}

.infor {
  width: 200px;
  height: 60px;
  margin-top: 10px;
  color: white;
  transition: background-color 0.3s ease; // 添加过渡效果
  border: 2px solid black; // 添加黑色边框
  border-radius: 10px; // 添加边框圆角
  display: flex; // 使用 Flexbox 布局
  align-items: center; // 垂直居中
  padding-left: 20px; // 添加内边距，使文字往右偏移
  &:hover {
    background-color: #525252; // 悬停时背景变为黑色
    color: white; // 可选：如果需要文字颜色也改变
  }
}

.custom-delete-btn {
  width: 25px; /* 调整宽度 */
  height: 20px; /* 调整高度 */
  margin-right: 10px;
  font-size: 12px; /* 调整字体大小 */
}

.button-icon {
  width: 100px;
  height: 100px;
  vertical-align: middle; /* 垂直居中 */
  margin-right: 8px; /* 图标与文字间距 */
}

</style>
